package com.acxy.ants.common.kit;

import com.acxy.ants.core.Const;
import com.acxy.ants.core.config.Modules;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-05-05
 */
public class PropKit {

    private static final Logger logger = LoggerFactory.getLogger(PropKit.class);

    protected static ConcurrentHashMap prop = null;

    protected static String[] ress = {};

    public PropKit() {
    }

    /**
     * Using the properties file. It will loading the properties file if not loading.
     *
     * @see #load(String, String)
     */
    public static void use(String... fileNames) {
        ress = new String[fileNames.length];
        for (int i = 0; i < fileNames.length; i++) {
            ress[i] = fileNames[i];
            load(fileNames[i], Const.DEFAULT_ENCODING);
        }
    }

    public static void use(String[] jars, String... fileNames) {
        ress = new String[fileNames.length];
        if(jars!=null && jars.length!=0){
            for(String jar: jars){
                List<InputStream> ins = Modules.getModuleFileInputStream(jar, 1);
                for(InputStream in: ins)load(in);
            }
        }
        for (int i = 0; i < fileNames.length; i++) {
            ress[i] = fileNames[i];
            load(fileNames[i], Const.DEFAULT_ENCODING);
            logger.debug("读取[{}]配置文 件...", fileNames[i]);
        }

    }

    /**
     * 根据流读取配置文件
     * @param inputStream
     */
    private static void load(InputStream inputStream){
        if (prop == null) prop = new ConcurrentHashMap();
        if (inputStream == null) {
            throw new IllegalArgumentException("Properties InputStream is null!");
        }
        try {
            Properties properties = new Properties();
            properties.load(new InputStreamReader(inputStream, Const.DEFAULT_ENCODING));
            logger.debug("模块配置："+properties);
            prop.putAll(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 读取文件
     *
     * @param fileName 资源配置名
     * @param encoding 编码集
     */
    private static void load(String fileName, String encoding) {
        if (prop == null) prop = new ConcurrentHashMap();
        InputStream inputStream = null;
        try {
            inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);        // properties.load(Prop.class.getResourceAsStream(fileName));
            if (inputStream == null) {
                throw new IllegalArgumentException("Properties file not found in classpath: " + fileName);
            }
            Properties properties = new Properties();
            properties.load(new InputStreamReader(inputStream, encoding));
            logger.debug("项目配置："+properties);
            prop.putAll(properties);
        } catch (IOException e) {
            throw new RuntimeException("Error loading properties file.", e);
        } finally {
            if (inputStream != null) try {
                inputStream.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }

    public static void clear() {
        prop.clear();
        prop = null;
    }

    public static ConcurrentHashMap getProp() {
        if (prop == null) {
            throw new IllegalStateException("Load propties file by invoking PropKit.use(String fileName) method first.");
        }
        return prop;
    }


    public static Object get(Object key) {
        return prop.get(key);
    }

    public static Object get(Object key, Object defaultValue) {
        return prop.get(key) == null ? defaultValue : prop.get(key);
    }

    public static String getStr(String key) {
        return String.valueOf(prop.get(key));
    }

    public static String getStr(String key, String defaultValue) {
        return prop.get(key) == null ? defaultValue : String.valueOf(prop.get(key));
    }

    public static Integer getInt(String key) {
        return Integer.parseInt(String.valueOf(prop.get(key)));
    }

    public static Integer getInt(String key, Integer defaultValue) {
        return prop.get(key) == null ? defaultValue : Integer.parseInt(String.valueOf(prop.get(key)));
    }

    public static Long getLong(String key) {
        return Long.parseLong(String.valueOf(prop.get(key)));
    }

    public static Long getLong(String key, Long defaultValue) {
        return prop.get(key) == null ? defaultValue : Long.parseLong(String.valueOf(prop.get(key)));
    }

    public static Boolean getBoolean(String key) {
        return Boolean.parseBoolean(String.valueOf(prop.get(key)));
    }

    public static Boolean getBoolean(String key, Boolean defaultValue) {
        return prop.get(key) == null ? defaultValue : Boolean.parseBoolean(String.valueOf(prop.get(key)));
    }

    public static boolean containsKey(String key) {
        return prop.containsKey(key);
    }

    public static void refresh() {
        logger.debug("loading {} ...", ress);
        use(ress);
    }

    //定时检测资源文件
    public static void useRefresh(final String... fileNames) {
        use(fileNames);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        Thread.sleep(2000);
                        System.out.println(new Date() + "线程定时开始检测资源文件...");
                        use(fileNames);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(runnable).start();
    }
}



